<template>
  <div
      class="function-bar-wrapper"
      :class="{ inline }"
      :style="inline ? undefined : wrapperStyle"
  >
    <div class="function-bar" :class="{ inline }">
      <el-button
          v-for="f in selectfeatures"
          :key="f.key"
          class="bar-btn"
          :type="activeSelectFeature===f.key ? 'primary' : 'info'"
          @click="toggleSelectionFeature(f.key)"
          @mouseenter="onFeatureHover(f)"
          @mouseleave="onFeatureLeave"
      >
        <img  :src="f.icon" alt="icon" class="custom-icon" />
        <!-- label is placed inside the button and positioned by CSS so it appears under this button -->
        <div v-show="hoveredFeature === f.key" class="feature-label" :aria-label="f.label ">
          {{ f.label  }}
        </div>
      </el-button>

      <el-button
          v-for="f in viewsfeatures"
          :key="f.key"
          class="bar-btn"
          :type="'info'"
          @click="toggleViewsfeatures(f.key)"
          @mouseenter="onFeatureHover(f)"
          @mouseleave="onFeatureLeave"
      >
        <img  :src="f.icon" alt="icon" class="custom-icon" />
        <div v-show="hoveredFeature === f.key" class="feature-label" :aria-label="f.label ">
          {{ f.label  }}
        </div>
      </el-button>

      <el-button
          v-for="f in modelVisiblefeatures"
          :key="f.key"
          class="bar-btn"
          :type="'info'"
          @click="toggleModelVisibleFeature(f.key)"
      >{{ f.label }}</el-button>

      <el-button
          v-for="f in infoVisiblefeatures"
          :key="f.key"
          class="bar-btn"
          :type="'info'"
          @click="toggleInfoVisibleFeature(f.key)"
      >{{ f.label }}</el-button>

      <el-select v-model="activeSectionView" clearable placeholder="剖视图" @change="clippingSectionView" style="width: 120px">
        <el-option
            v-for="item in sectionView"
            :key="item.key"
            :label="item.label"
            :value="item.key"
        />
      </el-select>
      <div class="slider-block">
        <div class="demonstration">剖面位置</div>
        <el-slider
            v-model="sectionViewPosition"
            @input="handleClippingOffsetChange"
            :min="-1"
            :max="1"
            :step="0.02"
            :disabled="sectiondisabled"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// Move the type above usages and keep script tidy
interface sectionViewDynamicObject {
  [key: string]: {
    PlaneTag: string;
    flag: boolean;
  };
}

import { defineProps, ref } from 'vue';
import eventBus from '@/utils/eventBus';
import selectVolumeIcon from '@/assets/icons/images/selectVolume.png';
import selectFaceIcon from '@/assets/icons/images/selectFace.png';
import selectEdgeIcon from '@/assets/icons/images/selectEdge.png';
import selectNodeIcon from '@/assets/icons/images/selectNode.png';

import frontIcon from '@/assets/icons/images/front.png';
import topIcon from '@/assets/icons/images/top.png';
import sideIcon from '@/assets/icons/images/side.png';
import backIcon from '@/assets/icons/images/back.png';
import bottomIcon from '@/assets/icons/images/bottom.png';
import rightIcon from '@/assets/icons/images/right.png';


const props = defineProps<{ treeWidth?: number; inline?: boolean }>();
const inline = props.inline;
const wrapperStyle = inline
  ? {}
  : {
      left: (props.treeWidth ?? 260) + 'px',
      width: `calc(100% - ${(props.treeWidth ?? 260)}px)`
    };

const activeSelectFeature = ref<string | null>(null);
const activeSectionView = ref<string>('');
const sectiondisabled = ref<boolean>(true);
const sectionViewPosition = ref(0);

// hover state (only store the hovered key; label is positioned by CSS)
const hoveredFeature = ref<string | null>(null);

function onFeatureHover(feature: any) {
  hoveredFeature.value = feature.key;
  console.log('[FunctionButton] hover:', feature.key, 'label=', feature.label);
  // safety: in case label is missing, log the full feature object
  if (!feature.label) console.warn('[FunctionButton] missing label for feature', feature);
}
function onFeatureLeave() {
  console.log('[FunctionButton] leave:', hoveredFeature.value);
  hoveredFeature.value = null;
}

const selectfeatures = [
  { key: 'Points', label: 'select Node', type: 'selection', icon: selectNodeIcon },
  { key: 'LineSegments', label: 'select Edge', type: 'selection', icon: selectEdgeIcon },
  { key: 'Mesh', label: 'select Face', type: 'selection', icon: selectFaceIcon },
  { key: 'Body', label: 'select Volume', type: 'selection', icon: selectVolumeIcon }
] as const;
const viewsfeatures = [
  { key: 'front', label: 'front', icon: frontIcon },
  { key: 'top', label: 'top', icon: topIcon },
  { key: 'side', label: 'side', icon: sideIcon },
  { key: 'back', label: 'back', icon: backIcon },
  { key: 'bottom', label: 'bottom', icon: bottomIcon },
  { key: 'right', label: 'right', icon: rightIcon },
] as const;
const sectionView = [
  { key: 'XY+', label: 'XY平面+'},
  { key: 'YZ+', label: 'YZ平面+'},
  { key: 'ZX+', label: 'ZX平面+'},
  { key: 'XY-', label: 'XY平面-'},
  { key: 'YZ-', label: 'YZ平面-'},
  { key: 'ZX-', label: 'ZX平面-'},
] as const;

// keep this as a plain object (type defined above)
const sectionViewfeatures: sectionViewDynamicObject = {
  'XY+': { PlaneTag: 'XY', flag: true },
  'YZ+': { PlaneTag: 'YZ', flag: true },
  'ZX+': { PlaneTag: 'ZX', flag: true },
  'XY-': { PlaneTag: 'XY', flag: false },
  'YZ-': { PlaneTag: 'YZ', flag: false },
  'ZX-': { PlaneTag: 'ZX', flag: false },
};

const infoVisiblefeatures = [
  { key: 'toggleFrame', label: '网格框'},
  { key: 'toggleNode', label: '节点'},
] as const;
const modelVisiblefeatures = [
  { key: 'toggleGeometryModel', label: '几何模型'},
  { key: 'toggleMeshModel', label: '网格模型'},
] as const;

function isSelection(key:string){
  return selectfeatures.find(f=>f.key===key)?.type==='selection'
}

function toggleSelectionFeature(feature: string) {
  const current = activeSelectFeature.value;
  const selection = isSelection(feature);
  // 再次点击同一个 -> 取消
  if (current === feature) {
    activeSelectFeature.value = null;
    if (selection) eventBus.emit('SelectionEventsStop', feature);
    else eventBus.emit('SelectionEvents', feature);
    return;
  }
  // 停掉旧的（如旧的是框选需停止）
  if (current) {
    if (isSelection(current)) eventBus.emit('SelectionEvents', feature);
    else eventBus.emit('SelectionEventsStop', feature);
  }
  // 激活新的
  activeSelectFeature.value = feature;
  if (selection) eventBus.emit('SelectionEvents', feature);
  else eventBus.emit('SelectionEventsStop', feature);
}
//- 切换视图功能按钮
function toggleViewsfeatures(feature: string) {
  eventBus.emit('viewFetureSelected', feature)
}
//- 切换模型信息显隐功能按钮
function toggleInfoVisibleFeature(feature: string) {
  eventBus.emit('infoVisibleFeatureSelected', feature)
}
//- 切换模型类型显隐功能按钮
function toggleModelVisibleFeature(feature: string) {
  eventBus.emit('modelVisibleFeatureSelected', feature)
}
//- 切换剖面视图功能按钮
function clippingSectionView(feature: string) {

  if(!feature) {
    eventBus.emit('sectionViewFeatureSelected', {"PlaneTag":'cancle',"flag":true});
    sectiondisabled.value = true
  }
  else  {
    eventBus.emit('sectionViewFeatureSelected', sectionViewfeatures[feature]);
    sectionViewPosition.value = 0
    sectiondisabled.value = false
  }

  // console.log("currentFeature:",currentFeature);
  // console.log("feature:",feature);
  // console.log("activeSectionView:",activeSectionView.value);
  // console.log("sectionViewfeatures[feature]:",sectionViewfeatures[feature]);
  // eventBus.emit('sectionViewFeatureSelected', sectionViewfeatures[feature]);
}
function handleClippingOffsetChange(value: any) {
  // console.log("activeSectionView in handleClippingOffsetChange:",activeSectionView);
  const OffsetChangeinfo ={"offsetValue":value,"sectionViewFeature":sectionViewfeatures[activeSectionView.value]}
  // console.log("OffsetChangeinfo:",OffsetChangeinfo);
  eventBus.emit('handleClippingOffsetChange', OffsetChangeinfo);
}
</script>

<style scoped lang="scss">
/* 红框位置：贴顶、从左侧树之后开始（overlay 模式通过 style 注入 left/width） */
.function-bar-wrapper {
  position: absolute;
  top: 0;
  height: 6vh; /* 顶条高度，可调 */
  display: flex;
  justify-content: center;
  align-items: stretch;
  pointer-events: none;
  z-index: 40;
  &.inline {
    position: relative;
    height: 100%;
    pointer-events: auto;
    flex: 1 1 auto; /* 在 header 内拉伸占中间区域 */
    justify-content: flex-start;
  }
}

.function-bar {
  pointer-events: auto;
  display: flex;
  flex: 1 1 auto;
  align-items: center;
  justify-content: flex-start;
  gap: 0.8vw;
  width: 100%;
  padding: 0 1vw;
  height: 100%;
  /* 平铺样式：去除半透明背景与阴影，只保留轻微底边线 */
  background: transparent;
  border-bottom: 0.4vh solid rgba(0,0,0,0.08);
  font-size: 1.5vh;
  box-shadow: none;
  border-radius: 0;
  &.inline {
    border-bottom: none;
    padding: 0 0.5vw;
  }
}

.bar-btn {
  position: relative; /* allow absolutely positioned label inside the button */
  overflow: visible; /* ensure the absolute label is visible outside button bounds */
  flex: 0 0 auto;
  display: flex !important;
  justify-content: center;
  align-items: center;
  height: 70%; /* 按钮高度相对条高度 */
  font-size: inherit;
  padding: 0; /* 用高度控制，不需要额外垂直内边距 */
  white-space: nowrap;
  /* 统一外观：占据等宽，Element Plus 默认样式保留 */
  &.inline { height: 80%; }
}

.feature-label {
  position: absolute;
  top: calc(100% + 6px); /* directly below the button */
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  color: #222; /* ensure visible text color */
  font-size: 12px; /* consistent size */
  font-weight: 600;
  border: 1px solid #ccc;
  padding: 5px 8px;
  border-radius: 3px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.15);
  white-space: nowrap;
  z-index: 9999;
  pointer-events: none; /* do not block mouse events */
}

/* 深色模式下的底边线调亮 */
:global(html.dark) .function-bar { border-bottom-color: rgba(255,255,255,0.15); }

/* 窄屏自适应换行：按钮两列或一列 */
@media (max-width: 900px) {
  .function-bar { flex-wrap: wrap; }
  .bar-btn { flex: 0 0 auto; height: 50%; } // 保持自适应，不强制 50% 宽
}
@media (max-width: 520px) {
  .bar-btn { flex: 1 1 100%; height: 45%; } // 超窄屏时占整行
}
// 剖面位置滑动条
.slider-block {
  max-width: 600px;
  display: flex;
  align-items: center;
}
.slider-block .el-slider {
  margin-top: 0;
  margin-left: 12px;
}
.slider-block .demonstration {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 44px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 0;
}
.slider-block .demonstration + .el-slider {
  flex: 0 0 100%;
}
</style>

<style lang="scss">
@use '@/assets/styles/custom-icon.scss';
</style>
